package com.dkd.findmyfriends;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.dkd.findmyfriends.HighScoresActivity.BuildGHSTableRunnable;
import com.dkd.findmyfriends.HighScoresActivity.GlobalTableRow;

public class Database {

	private static final String HOST = "http://96.126.114.16/paddock/";
	private static final String INSERT_HS = HOST + "insert_high_score.php";
	private static final String GET_TOP = HOST + "get_top_100.php";

	public static void insertScore(String username, Long time, Integer clicks, String gridSize) {
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("name", username));
		nameValuePairs.add(new BasicNameValuePair("time", String.valueOf(time == null ? -1 : time)));
		nameValuePairs.add(new BasicNameValuePair("clicks", String.valueOf(clicks == null ? -1 : clicks)));
		nameValuePairs.add(new BasicNameValuePair("size", gridSize));

		try {
			HttpPost post = new HttpPost(INSERT_HS);
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			new Query(null).execute(post);
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection", e);
		}
	}

	public static void getTop100Scores(String gridSize, BuildGHSTableRunnable run) {
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("size", gridSize));
		
		try {
			HttpPost post = new HttpPost(GET_TOP);
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			new Query(run).execute(post);
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection", e);
		}
		
//		String result = "";
//		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//		nameValuePairs.add(new BasicNameValuePair("size", gridSize));
//		InputStream is = null;
//		// http post
//		try {
//			HttpClient httpclient = new DefaultHttpClient();
//			HttpPost httppost = new HttpPost(GET_TOP);
//			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//			HttpResponse response = httpclient.execute(httppost);
//			HttpEntity entity = response.getEntity();
//			is = entity.getContent();
//		} catch (Exception e) {
//			Log.e("log_tag", "Error in http connection", e);
//		}
//		// //convert response to string
//		try {
//			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//			StringBuilder sb = new StringBuilder();
//			String line = null;
//			while ((line = reader.readLine()) != null) {
//				sb.append(line + "\n");
//			}
//			is.close();
//
//			result = sb.toString();
//		} catch (Exception e) {
//			Log.e("log_tag", "Error converting result", e);
//		}
//
//		// //parse json data
//		List<GlobalTableRow> ret = new ArrayList<GlobalTableRow>();
//		try {
//			JSONArray jArray = new JSONArray(result);
//			int clickCounter = 0;
//			int timeCounter = 0;
//			for (int i = 0; i < jArray.length(); i++) {
//				JSONObject data = jArray.getJSONObject(i);
//				if (!data.isNull("user_clicks") && !data.isNull("clicks")) {
//					GlobalTableRow tr = null;
//					if (clickCounter < ret.size()) {
//						tr = ret.get(clickCounter++);
//					} else {
//						tr = new GlobalTableRow();
//						ret.add(tr);
//						clickCounter++;
//					}
//					tr.userClicks = data.getString("user_clicks");
//					tr.clicks = data.getString("clicks");
//				}
//				if (!data.isNull("user_time") && !data.isNull("time")) {
//					GlobalTableRow tr = null;
//					if (timeCounter < ret.size()) {
//						tr = ret.get(timeCounter++);
//					} else {
//						tr = new GlobalTableRow();
//						ret.add(tr);
//						timeCounter++;
//					}
//					tr.userTime = data.getString("user_time");
//					long l = data.getLong("time");
//					tr.time = GameSettings.getTimeString(l);
//				}
//			}
//		} catch (JSONException e) {
//			Log.e("log_tag", "Error parsing data", e);
//		}
//		// return ret;
	}
	
	private static class Query extends AsyncTask<HttpPost, Void, JSONArray> {

		private BuildGHSTableRunnable run;
		
		protected Query(BuildGHSTableRunnable run) {
			this.run = run;  
		}
		
		protected JSONArray doInBackground(HttpPost... posts) {
			HttpClient c = new DefaultHttpClient();
			HttpPost p = posts[0];
			try {
				HttpResponse r = c.execute(p);
				HttpEntity entity = r.getEntity();
				InputStream is = entity.getContent();

				BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();

				String result = sb.toString();
				if(result == null || result.trim().equals("null")) {
					//nothing returned
					return null;
				}
				return new JSONArray(result);
			} catch (Exception e) {
				Log.e("log_tag", "Error in http connection", e);
			}
			return null;
		}

		protected void onProgressUpdate(Void... progress) {
			// setProgressPercent(progress[0]);
		}

		protected void onPostExecute(JSONArray jArray) {
			if (jArray == null) {
				if(run != null) {
					run.run();
				}
				return;
			}
			
			List<GlobalTableRow> ret = new ArrayList<GlobalTableRow>();
			try {
				int clickCounter = 0;
				int timeCounter = 0;
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject data = jArray.getJSONObject(i);
					if (!data.isNull("user_clicks") && !data.isNull("clicks")) {
						GlobalTableRow tr = null;
						if (clickCounter < ret.size()) {
							tr = ret.get(clickCounter++);
						} else {
							tr = new GlobalTableRow();
							ret.add(tr);
							clickCounter++;
						}
						tr.userClicks = data.getString("user_clicks");
						tr.clicks = data.getString("clicks");
					}
					if (!data.isNull("user_time") && !data.isNull("time")) {
						GlobalTableRow tr = null;
						if (timeCounter < ret.size()) {
							tr = ret.get(timeCounter++);
						} else {
							tr = new GlobalTableRow();
							ret.add(tr);
							timeCounter++;
						}
						tr.userTime = data.getString("user_time");
						long l = data.getLong("time");
						tr.time = GameSettings.getTimeString(l);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			run.rows = ret;
			run.run();
			// showDialog("Downloaded " + result + " bytes");
		}
	}

}
